<?php

namespace app\store\model;

use app\common\model\GiftsOrder as GiftsOrderModel;
use app\store\service\order\Export as Exportservice;
/**
 * 订单管理
 * Class Order
 * @package app\store\model
 */
class GiftsOrder extends GiftsOrderModel
{


    /**
     * 订单列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($query = [])
    {

        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        // 获取数据列表
        return $this->with(['goods.image', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->paginate(10, false, [
                'query' => \request()->request()
            ]);

    }


    /**
     * 财务管理订单列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getFinanceList($query = [])
    {

        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        $where = ['pay_status'=>20,'order.is_delete'=>0];
        // 获取数据列表
        return $this->with(['goods.image', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($where)
            ->order(['order.create_time' => 'desc'])
            ->paginate(10, false, [
                'query' => \request()->request()
            ]);

    }


    /**
     * 财务管理爆品礼订单导出
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function giftsFinanceExport($query = [])
    {
        header("Content-type:text/html;charset=utf-8");
        $mpName = '爆品订单';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getGiftsFinanceExport($query,0, $limit,true);

        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '订单编号', '商品信息', '订单总额', '实付款金额', '支付方式', '下单时间', '买家', '付款状态', '付款时间', '核销状态', '核销时间','微信支付交易号'
        ];


        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getGiftsFinanceExport($query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }


    /**
     * 财务管理储值订单导出列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getGiftsFinanceExport($query = [],$start, $limit,$count = false)
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        $where = ['pay_status'=>20,'order.is_delete'=>0];

        if($count==true){
            // 获取数据列表
            return $this->with(['goods.image', 'user'])
                ->alias('order')
                ->field('order.*')
                ->join('user', 'user.user_id = order.user_id')
                ->where($where)
                ->order(['order.create_time' => 'desc'])
                ->count();
        }
        // 获取数据列表
        $list =  $this->with(['goods.image', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($where)
            ->order(['order.create_time' => 'desc'])
            ->limit($start,$limit)
            ->select();
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '商品信息' => $this->filterOrderGoodsInfo($order),
                '订单总额' => $this->filterValue($order['order_price']),
                '实付款金额' => $this->filterValue($order['pay_price']),
                '支付方式' => $this->filterValue($order['pay_type']['text']),
                '下单时间' => $this->filterValue($order['create_time']),
                '买家' => $this->filterValue($order['user']['nickName']),
                '付款状态' => $this->filterValue($order['pay_status']['text']),
                '付款时间' => $this->filterTime($order['pay_time']),
                '核销状态' => $this->filterValue($order['write_status']['text']),
                '核销时间' => $this->filterTime($order['write_time']['value']),
                '微信支付交易号' => $this->filterValue($order['transaction_id']),
            ];

        }
        return  $dataArray;

    }


    /**
     * 订单列表(全部)
     * @param $dataType
     * @param array $query
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getListAll($query = [])
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        // 获取数据列表
        return $this->with(['goods.image', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->select();
    }



    /**
     * 打印订单列表
     * @param $dataType
     * @param array $query
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getExportList($query = [],$start, $limit,$count = false)
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        if($count==true){
            // 获取数据列表
            return $this->with(['goods.image', 'user'])
                ->alias('order')
                ->field('order.*')
                ->join('user', 'user.user_id = order.user_id')
                ->where('order.is_delete', '=', 0)
                ->order(['order.create_time' => 'desc'])
                ->count();
        }

        // 获取数据列表
        $list =  $this->with(['goods.image', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->limit($start,$limit)
            ->select();
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '商品信息' => $this->filterOrderGoodsInfo($order),
                '订单总额' => $this->filterValue($order['order_price']),
                '实付款金额' => $this->filterValue($order['pay_price']),
                '支付方式' => $this->filterValue($order['pay_type']['text']),
                '下单时间' => $this->filterValue($order['create_time']),
                '买家' => $this->filterValue($order['user']['nickName']),
                '付款状态' => $this->filterValue($order['pay_status']['text']),
                '付款时间' => $this->filterTime($order['pay_time']),
                '核销状态' => $this->filterValue($order['write_status']['text']),
                '核销时间' => $this->filterTime($order['write_time']['value']),
                '微信支付交易号' => $this->filterValue($order['transaction_id']),
            ];

        }
        return  $dataArray;

    }


    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

    /**
     * 日期值过滤
     * @param $value
     * @return string
     */
    private function filterTime($value)
    {

        if (!$value) return '';
        return $this->filterValue(date('Y-m-d H:i:s', $value));
    }


    /**
     * 格式化商品信息
     * @param $order
     * @return string
     */
    private function filterOrderGoodsInfo($order)
    {
        $content = '';
        foreach ($order['goods'] as $key => $goods) {
            $content .= ($key + 1) . ".商品名称：{$goods['gifts_title']}\n";
            $content .= "　购买数量：1\n";
            $content .= "　商品价格：{$goods['gifts_price']}元\n\n";
        }
        return $content;
    }


    /**
     * 订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportList($query)
    {

        header("Content-type:text/html;charset=utf-8");
        $mpName = '爆品订单';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getExportList($query,0, $limit,true);
        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }
        $xlsTitle = [
            '订单编号', '商品信息', '订单总额', '实付款金额', '支付方式', '下单时间', '买家', '付款状态', '付款时间', '核销状态', '核销时间','微信支付交易号'
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getExportList($query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }




    /**
     * 设置检索查询条件
     * @param $query
     */
    private function setWhere($query)
    {

        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('order_no|user.nickName', 'like', '%' . trim($query['search']) . '%');
        }

        if (isset($query['start_time']) && !empty($query['start_time'])) {
            $this->where('order.create_time', '>=', strtotime($query['start_time']));
        }
        if (isset($query['end_time']) && !empty($query['end_time'])) {
            $this->where('order.create_time', '<', strtotime($query['end_time']) + 86400);
        }
        if (isset($query['pay_status']) && !empty($query['pay_status'])) {
            $query['pay_status'] > -1 && $this->where('pay_status', '=', $query['pay_status']);
        }
        if (isset($query['pay_type']) && !empty($query['pay_type'])) {
            $query['pay_type'] > -1 && $this->where('pay_type', '=', $query['pay_type']);
        }
        if (isset($query['write_status']) && !empty($query['write_status'])) {
            $query['write_status'] > -1 && $this->where('write_status', '=', $query['write_status']);
        }

    }


    /**
     * 获取csv文件中的数据
     * @return array|bool
     */
    private function getCsvData()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = \request()->file('iFile');
        if (empty($file)) {
            $this->error = '请上传发货模板';
            return false;
        }
        // 设置区域信息
        setlocale(LC_ALL, 'zh_CN');
        // 打开上传的文件
        $csvFile = fopen($file->getInfo()['tmp_name'], 'r');
        // 忽略第一行(csv标题)
        fgetcsv($csvFile);
        // 遍历并记录订单信息
        $orderList = [];
        while ($item = fgetcsv($csvFile)) {
            if (!isset($item[0]) || empty($item[0]) || !isset($item[1]) || empty($item[1])) {
                $this->error = '模板文件数据不合法';
                return false;
            }
            $orderList[] = $item;
        }
        if (empty($orderList)) {
            $this->error = '模板文件中没有订单数据';
            return false;
        }
        return $orderList;
    }









}
